import sys,math
import threading
import os
import shutil
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox
from PyQt5.QtGui import *
from numba import jit
from TDC import *
from cursorsetting import *
from Expsetting import *
from PyQt5.Qt import *
from pyqtgraph import PlotWidget
from PyQt5 import QtCore
import numpy as np
import pyqtgraph as pq
import datetime
import matplotlib
import matplotlib.pyplot as plt
import time
from collections import Counter
from PyQt5.QtChart import QChartView, QChart, QLineSeries, QValueAxis, QScatterSeries


# try:
#     import QuTAG
# except:
#     print("Time Tagger wrapper QuTAG.py is not in the search path.")
# qutag = QuTAG.QuTAG()


# count2=0
#@jit
def rep(data):
    for i in range(1000):
        data.append(1,i)
@jit
def re(d):
    for i in range(100):
        d[i][0]=i
        d[i][1]=i*i



@jit
def cal(data1, data2):
    # global count2
    channeltime1 = np.zeros(shape=(len(data1), 1))
    channeltime2 = np.zeros(shape=(len(data1), 1))
    channeltime3 = np.zeros(shape=(len(data1), 1))
    sweeps = 0
    det1 = 0
    det2 = 0
    det3 = 0
    count1 = 0
    count2 = 0
    count3 = 0
    coin12 = 0
    coin12 = 0
    coin13 = 0
    coin23 = 0
    coin123 = 0
    print(len(data1))
    for i in np.arange(0, len(data1), 1):
        if data2[i] == 4:
            sweeps = sweeps + 1
            if det1 != 0 and det2 != 0:
                coin12 = coin12 + 1
                if det3 != 0:
                    coin13 = coin13 + 1
                    coin23 = coin23 + 1
                    coin123 = coin123 + 1
                else:
                    a = 1
            elif det1 != 0 and det3 != 0:
                coin13 = coin13 + 1
            elif det2 != 0 and det3 != 0:
                coin23 = coin23 + 1
            else:
                a = 1
            det1 = 0
            det2 = 0
            det3 = 0
        elif data2[i] == 1:# and cursor_1_1 < data1[i] < cursor_1_2:  # jiacursor
            channeltime1[i] = data1[i]
            det1 = det1 + 1
            count1 = count1 + 1
        elif data2[i] == 2:# and cursor_2_1 < data1[i] < cursor_2_2:
            channeltime2[i] = data1[i]
            det2 = det2 + 1
            count2 = count2 + 1
        elif data2[i] == 3:# and cursor_3_1 < data1[i] < cursor_3_2:
            channeltime3[i] = data1[i]
            det3 = det3 + 1
            count3 = count3 + 1
        else:
            a = 0

    return sweeps, count1, count2, count3, coin12, coin13, coin23, coin123, channeltime1, channeltime2, channeltime3


class SetExpTime(QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(SetExpTime, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set ExpTime")
        self.Button_SetExpTime_ok.clicked.connect(self.ExpTime)

    def ExpTime(self):
        self.ExpTime_set = self.Set_Exp_Time.text()
        self.ExposureTime_set = self.Set_Exp_ExposureTime.text()
        self.Set_Exp_Time.setPlaceholderText('self.ExpTime_set')
        self.close()
        return self.ExpTime_set, self.ExposureTime_set


class SetCursor(QDialog, Ui_CursorSetting):
    def __init__(self, parent=None):
        super(SetCursor, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Set Cursor")
        self.Set_Cursorsetting_ok.clicked.connect(self.setcursor)

    def setcursor(self):
        cursor_1_1 = self.Set_Cursor1_Channel1.text()
        cursor_1_2 = self.Set_Cursor2_Channel1.text()
        cursor_2_1 = self.Set_Cursor1_Channel2.text()
        cursor_2_2 = self.Set_Cursor2_Channel2.text()
        cursor_3_1 = self.Set_Cursor1_Channel3.text()
        cursor_3_2 = self.Set_Cursor2_Channel3.text()
        self.close()
        return cursor_1_1, cursor_1_2, cursor_2_1, cursor_2_2, cursor_3_1, cursor_3_2


class Window(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        #self.ui=Ui_MainWindow()
        self.setupUi(self)
        self.stop_trigger = 0
        self.Time_Waiting_GetTimestamps = 1
        #测量时间初始值
        self.ExpTimeSetting = 10000
        self.ExposureTimeSetting = 50  # ms
        self.g12 = 0
        self.g13 = 0
        self.g23 = 0
        self.alpha_1_23 = 0
        #光标设置
        self.channel1_cursor1 = 153500
        self.channel1_cursor2 = 155000
        self.channel2_cursor1 = 200000
        self.channel2_cursor2 = 210000
        self.channel3_cursor1 = 200000
        self.channel3_cursor2 = 210000

        self.Time_Start = datetime.datetime.now()
        self.Button_Start.clicked.connect(self.starting)
        self.Button_Stop.clicked.connect(self.stopping)
        self.action_Exptime.triggered.connect(self.SetExpTime)

        series1 = QLineSeries()
        series1.clear()
        series1.setName('cursor')
        self._chart = QChart()
        self._chart.addSeries(series1)
        print('xunhuanchu', datetime.datetime.now())
        rep(series1)
        print('xunhuan2', datetime.datetime.now())


        self.Counting_Channel_1.setChart(self._chart)
        self.axisx = QValueAxis()
        self.axisx.setRange(-1, 100)
        self.axisy = QValueAxis()
        self.axisy.setRange(0, 10)
        self._chart.setAxisX(self.axisx, series1)
        self._chart.setAxisY(self.axisy, series1)



    def SetExpTime(self):
        self.SetExpTimeWindow = SetExpTime()
        self.SetExpTimeWindow.exec_()
        self.exptime = self.SetExpTimeWindow.ExpTime()
        self.SetExpTimeWindow.Set_Exp_Time.setPlaceholderText('self.ExpTime_set')
        self.ExpTimeSetting = float(self.exptime[0])
        self.ExposureTimeSetting = int(float(self.exptime[1])*1000)


    def stopping(self):
        self.stop_trigger = 1

    def starting(self):
        self.count_sweeps = 0
        self.stop_trigger = 0
        self.sweeps = 0



        self.Time_Exp_Start = datetime.datetime.now()






        if self.stop_trigger == 0:
            self.timer = pq.QtCore.QTimer()
            self.timer.timeout.connect(self.update_data)
            self.timer.start(self.ExposureTimeSetting)  # shezhiTDCduqujiange
        else:
            a = 1

    def update_data(self):
        Time_Exp_Stop = datetime.datetime.now()
        Exp_Time = (Time_Exp_Stop - self.Time_Exp_Start).total_seconds()
        print(datetime.datetime.now())
        self.series = QLineSeries()
        self._chart.removeSeries(self.series)
        self.series.clear()

        self.series = QLineSeries()
        # self.series.clear()
        self.series.setName('曲线')
        self._chart.addSeries(self.series)
        #self._chart = QChart()
    #    self._chart.addSeries(series)
        xx=np.zeros(shape=(100,2))

        for i in range(100):
            xx[i][0]=i
            xx[i][1]=np.random.randint(1,10)
        #re(xx)
        print('xunhunkais', datetime.datetime.now())
        for b in xx:
            self.series.append(b[0],b[1])
        print(type(self._chart.series()[0]))
        print('xunhuan1',datetime.datetime.now())

        #print(self._chart.series()[0])


        self._chart.setAxisX(self.axisx,self.series)
        self._chart.setAxisY(self.axisy, self.series)


        print(datetime.datetime.now())
        '''
        # print(Exp_Time)
        if self.stop_trigger == 0 and Exp_Time < self.ExpTimeSetting:


            self.count_sweeps = self.count_sweeps + result[0]

            # 数据展示
            self.Result_Counts_alpha1_23.setPlaceholderText('aaa')
            self.Result_Sweeps.setText(str(self.count_sweeps))

            self.plot_data1 = result[8].T.tolist()
            self.plot_data1 = self.plot_data1[0]
            self.plot_data1 = [x for x in self.plot_data1 if x != 0.0]
            if len(self.plot_data1) != 0:
                self.datab = Counter(self.plot_data1)
                self.datab = self.datab.most_common(len(self.datab))
                self.datab = np.array(self.datab)
                self.datab = np.transpose(self.datab)
                self.gg = self.datab.T[np.lexsort(self.datab[::-1, :])].T
                self.curve1.setData(self.gg[0], self.gg[1])

        else:
            self.stop_trigger = 1
'''
if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())
